<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="店铺" prop="shopId">
        <select-basic-shop v-model="queryParams.shopId"/>
      </el-form-item>
      <el-form-item label="微信号" prop="wechat">
        <el-input
          v-model="queryParams.wechat"
          placeholder="请输入微信号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="充值时间" prop="payTime">
        <el-date-picker
          v-model="queryParams.payTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待执行" value="going"/>
          <el-option label="已完结" value="finish"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发起时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['operation:business-pay:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['operation:business-pay:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="编号" align="center" prop="id" width="60"/>
      <el-table-column label="店铺" align="center" prop="shopId_dictText" width="200"/>
      <el-table-column label="微信号" align="center" prop="wechat" width="120"/>
      <el-table-column label="本月已申请金额" align="center" prop="thisMonthAppliedAmount"
                       width="100"/>
      <el-table-column label="上月账户余额" align="center" prop="lastMonthBalance" width="100"/>
      <el-table-column label="本次申请账户余额" align="center" prop="theAppliedAmount" width="100"/>
      <el-table-column label="本月补单金额合计" align="center" prop="thisMonthBusinessMoney"
                       width="100"/>
      <el-table-column label="应余余额" align="center" prop="remainingBalance" width="100"/>
      <el-table-column label="差额" align="center" prop="difference" width="100"/>
      <el-table-column label="微信余额截图" align="center" prop="wechatBalanceImg">
        <template #default="scope">
          <image-preview :src="scope.row.wechatBalanceImg"/>
        </template>
      </el-table-column>
      <el-table-column label="申请金额" align="center" prop="payMoney" width="100"/>
      <el-table-column label="备注" align="center" prop="remark" width="100"/>
      <el-table-column
        label="完结时间"
        align="center"
        prop="payTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="状态" align="center" prop="status" width="100" fixed="right">
        <template #default="scope">
          <el-tag v-if="scope.row.status=='going'" type="warning">待执行</el-tag>
          <el-tag v-if="scope.row.status=='finish'" type="success">已完结</el-tag>

        </template>
      </el-table-column>
      <el-table-column label="发起人" align="center" prop="creator_dictText" width="100"/>
      <el-table-column
        label="发起时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />


      <el-table-column label="操作" align="center" min-width="160px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleFinish(scope.row)"
            v-hasPermi="['operation:business:admin']"
            v-if="scope.row.status=='going'"
          >
            完结
          </el-button>

          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['operation:business-pay:update']"
            v-if="scope.row.status=='going'"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-if="scope.row.status=='going'"
            v-hasPermi="['operation:business-pay:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BusinessPayForm ref="formRef" @success="getList"/>
</template>s

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {BusinessPay, BusinessPayApi} from '@/api/business/operation/business/pay'
import BusinessPayForm from './BusinessPayForm.vue'
import {hasPermission} from "@/directives/permission/hasPermi";
import {useUserStore} from "@/store/modules/user";

/** 业务-运营-补单-账号充值 列表 */
defineOptions({name: 'OperationBusinessPay'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BusinessPay[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  shopId: undefined,
  wechat: undefined,
  thisMonthAppliedAmount: undefined,
  lastMonthBalance: undefined,
  theAppliedAmount: undefined,
  thisMonthBusinessMoney: undefined,
  remainingBalance: undefined,
  difference: undefined,
  wechatBalanceImg: undefined,
  payMoney: undefined,
  payTime: [],
  status: undefined,
  remark: undefined,
  createTime: [],
  processInstanceId: undefined,
    shopIds:[],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const userStore = useUserStore()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  if (!hasPermission(['operation:business:admin'])) {
    let shopIds = userStore.user.shopIds
    // 检查shopIds是否为空（包括null、undefined、空字符串、纯空格）
    if (!shopIds || typeof shopIds !== 'string' || shopIds.trim() === '') {
      // 为空时弹出错误提示
      message.error('请先进行店铺授权');
      return; // 终止后续逻辑，避免继续执行
    } else {
      // 将字符串按逗号分割为数组，并转换为数字类型（根据需要选择是否转换）
      queryParams.shopIds = shopIds
        .split(',')
        .filter(shopId => shopId.trim() !== '') // 过滤空值
        .map(shopId => {
          // 这里根据实际需求决定是保留字符串还是转为数字
          const num = Number(shopId);
          return isNaN(num) ? shopId : num; // 转换为数字，转换失败则保留原字符串
        });
    }
  }
  try {
    const data = await BusinessPayApi.getBusinessPayPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BusinessPayApi.deleteBusinessPay(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

const handleFinish = async (row: any) => {
  await message.confirm("是否确认完结编号为：" + row.id + " 的数据项？")
  let form = {
    id: row.id,
    shopId: row.shopId,
    status: 'finish',
  }
  const data = form as unknown as BusinessPay
  await BusinessPayApi.updateBusinessPay(data)
  message.success("操作成功！")
  await getList()

}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BusinessPayApi.exportBusinessPay(queryParams)
    download.excel(data, '业务-运营-补单-账号充值.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
